package com.SRMS.service;

import com.SRMS.dao.RevokeRecordForAdminDAO;
import com.SRMS.dao.RightRecordDAO;
import com.SRMS.dao.RightToUseStudyRoomDAO;
import com.SRMS.dao.StudyRoomDAO;
import com.SRMS.domain.RevokeRecordForAdmin;
import com.SRMS.domain.RightRecord;
import com.SRMS.domain.RightToUseStudyRoom;
import com.SRMS.domain.StudyRoom;
import com.SRMS.utils.JDBCUtilsByDruid;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author Albert
 * @version 1.0
 * @date 2023/12/19-20:08
 * @describe 管理员管理自习室使用权服务类
 */
public class RightManageService {
    private RightRecordDAO rightRecordDAO = new RightRecordDAO();
    private RightToUseStudyRoomDAO rightToUseStudyRoomDAO = new RightToUseStudyRoomDAO();
    private StudyRoomDAO studyRoomDAO = new StudyRoomDAO();
    private RevokeRecordForAdminDAO revokeRecordForAdminDAO = new RevokeRecordForAdminDAO();

    public List<RevokeRecordForAdmin> revokeRecordForAdminList(){
        return revokeRecordForAdminDAO.queryMulti("SELECT * FROM revokeRecordForAdmin", RevokeRecordForAdmin.class);
    }

    /**
     * 撤销学生的使用权
     * @param studentId 学号
     * @param administratorId 管理员工号
     * @param revokeReason 撤销原因
     * @return 撤销结果（true/false）
     */
    public boolean revokeRightByStudentId(String studentId, String administratorId, String revokeReason){
        RightToUseStudyRoom rightToUseStudyRoom = getRightByStuId(studentId);
        StudyRoom studyRoom = getStudyRoomById(rightToUseStudyRoom.getStudyRoomId());
        if(rightToUseStudyRoom == null){
            return false;
        }
        //获取申请时间
        LocalDateTime ldt = rightToUseStudyRoom.getApplicationTime().toLocalDateTime();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String applicationTime = dateTimeFormatter.format(ldt);
        //获取归还时间（也是撤销时间）
        LocalDateTime ldt2 = LocalDateTime.now();
        String discontinuingUseTime = dateTimeFormatter.format(ldt2);

        int newRemainingSeats = studyRoom.getRemainingSeats() + 1;
        int result1 = 0;
        int result2 = 0;
        int result3 = 0;
        int result4 = 0;
        String sql1 = "DELETE FROM rightToUseStudyRoom WHERE studentId = ?";
        String sql2 = "UPDATE studyRoom SET remainingSeats = ? WHERE studyRoomId = ?";
        String sql3 = "INSERT INTO studyRoomUsageRecord VALUES (?, ?, ?, ?, ?)";
        String sql4 = "INSERT INTO revokeRecord VALUES (?, ?, ?, ?, ?, ?)";
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        //使用事务保证数据一致性
        try {
            connection = JDBCUtilsByDruid.getConnection();
            //将connection设置为不自动提交
            connection.setAutoCommit(false);
            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.setString(1, studentId);
            result1 = preparedStatement.executeUpdate();
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.setInt(1, newRemainingSeats);
            preparedStatement.setString(2, studyRoom.getStudyRoomId());
            result2 = preparedStatement.executeUpdate();
            preparedStatement = connection.prepareStatement(sql3);
            preparedStatement.setString(1, studyRoom.getStudyRoomId());
            preparedStatement.setString(2, studentId);
            preparedStatement.setString(3, applicationTime);
            preparedStatement.setString(4, discontinuingUseTime);
            preparedStatement.setString(5, rightToUseStudyRoom.getRightId());
            result3 = preparedStatement.executeUpdate();
            preparedStatement = connection.prepareStatement(sql4);
            preparedStatement.setString(1, rightToUseStudyRoom.getRightId());
            preparedStatement.setString(2, administratorId);
            preparedStatement.setString(3, discontinuingUseTime);
            preparedStatement.setString(4, revokeReason);
            preparedStatement.setString(5, studentId);
            preparedStatement.setString(6, studyRoom.getStudyRoomId());
            result4 = preparedStatement.executeUpdate();
            if(result1 == 0 || result2 == 0 || result3 == 0 || result4 == 0){
                //撤销回滚
                try {
                    connection.rollback();//默认回滚到事务开始时的状态
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }

                return false;
            }
            //提交事务
            connection.commit();

        } catch (SQLException e) {
            //撤销回滚
            try {
                connection.rollback();//默认回滚到事务开始时的状态
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }

            throw new RuntimeException(e);

        } finally {
            JDBCUtilsByDruid.close(null, preparedStatement, connection);
        }

        return true;
    }

    /**
     * 根据自习室编号查询自习室
     * @param studyRoomId
     * @return 返回查询到的自习室
     */
    public StudyRoom getStudyRoomById(String studyRoomId){
        return studyRoomDAO.querySingle("SELECT * FROM studyRoom WHERE studyRoomId=?", StudyRoom.class, studyRoomId);
    }

    /**
     * 根据学号查询自习室使用权
     * @return 返回使用权对象
     */
    public RightToUseStudyRoom getRightByStuId(String studentId){
        return rightToUseStudyRoomDAO.querySingle("SELECT * FROM rightToUseStudyRoom WHERE studentId = ?", RightToUseStudyRoom.class, studentId);
    }

    /**
     * 查询所有使用权信息
     * @return 使用权列表
     */
    public List<RightRecord> rightList(){
        return rightRecordDAO.queryMulti("SELECT * FROM rightRecord", RightRecord.class);
    }
}
